package jsoup;

import cn.demoncat.util.http.JsoupUtil;
import cn.demoncat.util.lang.JsonUtil;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.select.Elements;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 统计局地址区划
 *
 * @author 延晓磊
 * @since 2024年08月21日
 */
public class AreaQuery {

    @Test
    public void test(){
        System.out.println(JsonUtil.toStr(get()));
    }

    /**
     * 获取地址区划
     *
     * @return
     */
    public static List<StatsArea> get(){
        // 统计局地址，不包含台湾、香港、澳门
        String URL = "https://www.stats.gov.cn/sj/tjbz/tjyqhdmhcxhfdm/2023/";
        // 获取省
        List<StatsArea> provinces = JsoupUtil.get(URL + "index.html").select(".provincetr td a").stream().map(o -> {
            StatsArea area = new StatsArea();
            area.setUrl(o.attr("href"));
            area.setName(o.text());
            area.setId(area.getUrl().substring(0, 2) + "0000");
            area.setParentId("000000");
            return area;
        }).collect(Collectors.toList());
        // 获取市
        List<StatsArea> cities = new ArrayList<>();
        for (StatsArea province : provinces) {
            JsoupUtil.get(URL + province.getUrl()).select(".citytr").forEach(doc ->{
                Elements tds = doc.select("td a");
                if (CollectionUtils.isEmpty(tds)) {
                    tds = doc.select("td");
                }
                StatsArea area = new StatsArea();
                area.setUrl(tds.get(1).attr("href"));
                area.setName(tds.get(1).text());
                area.setId(tds.get(0).text().substring(0, 6));
                area.setParentId(province.getId());
                cities.add(area);
            });
        }
        // 获取县
        List<StatsArea> counties = new ArrayList<>();
        for (StatsArea city : cities) {
            if (StringUtils.isNotBlank(city.getUrl())) {
                JsoupUtil.get(URL + city.getUrl()).select(".countytr").forEach(doc ->{
                    Elements tds = doc.select("td a");
                    if (CollectionUtils.isEmpty(tds)) {
                        tds = doc.select("td");
                    }
                    StatsArea area = new StatsArea();
                    area.setName(tds.get(1).text());
                    area.setId(tds.get(0).text().substring(0, 6));
                    area.setParentId(city.getId());
                    counties.add(area);
                });
            }
        }
        provinces.addAll(cities);
        provinces.addAll(counties);
        return provinces;
    }


    /**
     * 地址
     */
    @Data
    public static class StatsArea {

        // ID
        private String id;
        // 父ID
        private String parentId;
        // 名称
        private String name;
        // URL
        private String url;
    }
}